import React from 'react';
import {Table, Button, Card, Form, Input, Popconfirm, Select} from 'antd';
import StudentService from '../../service/StudentService';
import CountryService from '../../service/CountryService';
import moment from 'moment';

const Option = Select.Option;
export default class StudentList extends React.Component {

    state = {
        title:'Student列表',
        data: [],
        pagination: {pageSize: 10, current: 1,size:'middle'},
        pagStart: {pageSize: 10, current: 1,size:'middle'},
        search: '',
        //列表加载
        tableLoading: false,
        departmentList : [],//下拉框查询数据
        searchParam : {},
        tableList:[],
        countryList:[],
        loading:false
    };

    constructor(props) {
        super(props);
    }

    componentDidMount() {
        this.fetch(this.state.pagination);
        this.fetchCountry();
    }

    //查询方法-按姓名、国家查询
    fetch(pagination) {
        console.log('pagination.......',pagination);
        this.setState({
            loading: true,
        });
        let pager = {
            query: this.state.search,
            page: pagination.current - 1,
            size: pagination.pageSize,
            current: pagination.current,
            //sort:['receiptDate', 'DESC']
        };
        console.log('pager.......',pager);
        StudentService.getList(pager).done(data=>{
            console.log('data',data.entity);
            if (data.entity) {
                this.setState({
                    tableList: data.entity,
                    loading: false,
                    pagination: {
                        total: parseInt(data.headers['X-Total-Count']),
                        pageSize: this.state.pagination.pageSize,
                        current: pager.current
                    }
                })
            }
        })
    }

    //查询方法-按用户名查询
    fetchByUserName(pagination) {
        console.log('pagination.......',pagination);
        this.setState({
            loading: true,
        });

        StudentService.getByLogin(this.state.search).done(data=>{
            console.log('userData',data.entity);
            if (data.entity) {
                let pager = {
                    query: this.state.search,
                    page: pagination.current - 1,
                    size: pagination.pageSize,
                    current: pagination.current,
                };

                this.setState({
                    tableList: data.entity,
                    loading: false,
                    pagination: {
                        total: parseInt(data.headers['X-Total-Count']),
                        pageSize: this.state.pagination.pageSize,
                        current: pager.current
                    }
                });

            } else {
                this.setState({
                    tableList: [],
                    loading: false,
                });
                this.forceUpdate();
            }
        })
    }

    fetchCountry(){
        CountryService.getList({size: 1000}).done((res)=>{
            this.setState({countryList:res.entity})
        })
    }

    //查询方法
    searchClick() {
        let search = '';
        let params = this.state.searchParam;

        //如果按照用户名查询，其他查询条件都清空
        if (params.userName) {
            search += params.userName;

            //清空其他查询条件
            this.state.searchParam.firstName = "";
            this.state.searchParam.lastName = "";
            this.state.searchParam.countryId = "";
            this.forceUpdate();

            //按用户名查询
            this.state.search = search;
            this.fetchByUserName(this.state.pagStart);
        } else {
            //其他查询条件
            if (params.firstName) {
                search += 'firstName=like='+params.firstName+';';
            }

            if (params.lastName) {
                search += 'lastName=like='+params.lastName+';';
            }

            if (params.countryId) {
                search ? search += "" : search = "";
                search += 'country.id=='+params.countryId+';';
            }

            //按姓名、国家查询
            this.state.search = search;
            this.fetch(this.state.pagStart);
        }
    }
// {/*<Card title={this.state.title} className="user" extra={<a onClick={()=>{*/}
// {/*this.props.history.push("/student/add");*/}
// {/*}}>新增</a>}>*/}
    render() {
        return (
            <Card title={this.state.title} className="user">
                <Form layout="inline" style={{marginBottom:'20px'}}>
                    <Form.Item label={'姓名：'}>
                        <Input placeholder="firstName"
                               value={this.state.searchParam.firstName}
                               style={{width:'150px'}}
                               onChange={(e)=>{
                                   this.state.searchParam.firstName = e.target.value
                                   this.forceUpdate();
                               }}
                        />
                        <Input placeholder="lastName"
                               value={this.state.searchParam.lastName}
                               style={{width:'150px',marginLeft:'5px'}}
                                  onChange={(e)=>{
                                      this.state.searchParam.lastName = e.target.value
                                      this.forceUpdate();
                                  }}
                        />
                    </Form.Item>

                    <Form.Item label={'国家：'}>
                        <Select placeholder={"请选择国家"}
                                style={{width:'200px'}}
                                value={this.state.searchParam.countryId}
                                onChange={(e)=>{
                                    this.state.searchParam.countryId = e;
                                    this.forceUpdate();
                                }}
                        >
                            {this.state.countryList.map((item, i) => {
                                return (
                                    <Option key={i} value={item.id}>{item.cnName+'('+item.enName+')'}</Option>
                                )
                            })}
                        </Select>
                    </Form.Item>

                    <Form.Item label={'用户名：'}>
                        <Input placeholder="userName"
                               style={{width:'150px'}}
                               onChange={(e)=>{
                                   this.state.searchParam.userName = e.target.value
                               }}
                        />
                    </Form.Item>

                    <Form.Item>
                        <Button
                            type="primary"
                            icon="search"
                            onClick={()=>{
                                this.searchClick();
                            }}
                        >搜索</Button>
                    </Form.Item>
                </Form>
                <Table
                    rowKey={record => record.id}
                    bordered={true}
                    loading={this.state.loading}
                    dataSource={this.state.tableList}
                    columns={[
                        {title:"姓名", align:'center', dataIndex: 'name', key: 'cnName',render : (text, record) => {
                            return(<div>{(record.firstName||'')+' '+(record.lastName||'')}</div>)
                        }},
                        {title:"昵称", align:'center', dataIndex: 'nickName', key: 'nickName'},
                        {title:"国家", align:'center', dataIndex: 'country', key: 'country',render : (text, record) => {
                            return(<div>{record.country?record.country.cnName:''}</div>)
                        }},
                        {title:"性别", align:'center', dataIndex: 'gender', key: 'gender',render : (text, record) => {
                            if(record.gender){
                                return(<div>{record.gender==='Male'?'男':'女'}</div>)
                            }else{
                                return('')
                            }}
                        },
                        {title:"来华时间", align:'center', dataIndex: 'dateCameToChina', key: 'dateCameToChina',render : (text, record) => {
                            return(<div>{record.dateCameToChina?moment(record.dateCameToChina).format('YYYY/MM/DD HH:mm:ss'):''}</div>)
                        }},
                        {title:"积分", align:'center', dataIndex: 'score', key: 'score'},
                        {title:"操作", align:'center', dataIndex: 'operation', key: 'operation',
                            render : (text, record) => {
                                return (
                                    <div className='btn-cen-div'>
                                        <a onClick={()=>{
                                            this.props.history.push("/student/view/" + record.id);
                                        }}>详情</a>

                                        <a onClick={()=>{
                                            this.props.history.push("/student/integral/" + record.id);
                                        }}>修改积分</a>

                                        <Popconfirm placement="top" okText="确认" cancelText="关闭" title="是否确定删除?" onConfirm={() =>{
                                            StudentService.deleteOne(record.id).done(()=>{
                                                this.fetch(this.state.pagination);
                                            })
                                        }}>
                                            <a>删除</a>
                                        </Popconfirm>
                                    </div>
                                )
                            }
                        },
                    ]}
                    pagination={this.state.pagination}
                    onChange={this.fetch.bind(this)}
                />
            </Card>
        )
    }
}